"""
Original WebFX Chart author: Emil A Eklund
Original WebFX Chart code: http://webfx.eae.net/dhtml/chart/chart.html
Widget author: Ansel Halliburton (ansel@alum.berkeley.edu)
Widget code: http://code.google.com/p/tg-webfxchart/
License: MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import pkg_resources
from turbogears.widgets import JSLink, CSSLink, Widget, WidgetDescription, register_static_directory

#mod_name = "webfxchart"
mod_name = "WebFXChart"

js_dir = pkg_resources.resource_filename(mod_name, "static")

register_static_directory(mod_name, js_dir)

excanvas_js = JSLink(mod_name, "excanvas.js")
chart_js = JSLink(mod_name, "chart.js")
canvaschartpainter_js = JSLink(mod_name, "canvaschartpainter.js")
canvaschart_css = CSSLink(mod_name, "canvaschart.css")


class WebFXChart(Widget):
    """
    WebFXChart(style, options, divElement, datasourceArray)
    
    WebFXChart is a widget wrapper around the WebFX Chart and associated
    CSS/JS code.  Its implementation is similar to EasyPlot, a widget
    wrapper for PlotKit.
    
    WebFX Chart: http://webfx.eae.net/dhtml/chart/chart.html
    PlotKit: http://www.liquidx.net/plotkit/
    PlotKit TG widget: http://cheeseshop.python.org/pypi/PlotKit/
    EasyPlot TG widget: http://inet6.blogspot.com/2006/06/plotkit-with-easyplot-in-turbogears.html
    """
    
    STYLE_MAP = {
        'bar': 'CHART_BAR',
        'stacked_bar': 'CHART_BAR | CHART_STACKED',
        'area': 'CHART_AREA',
        'stacked_area': 'CHART_AREA | CHART_STACKED',
        'line': 'CHART_LINE',
        'stacked_line': 'CHART_LINE | CHART_STACKED'
    }
    
    javascript = [excanvas_js, chart_js, canvaschartpainter_js]
    css = [canvaschart_css]
    
    params = ["id", "style", "width", "height", "data", 'labels', 'colors', 'x_labels', 'x_ticks', 'y_ticks', 'y_max']
    params_doc = {'id' : 'Chart <div> id (str)',
                  'style' : "one of %s (str)" % str(STYLE_MAP.keys()),
                  'width' : 'Chart width in pixels (int)',
                  'height' : 'Chart height in pixels (int)',
                  'data': 'list of 3-tuples, where each 3-tuple consists of (name, color, series data)',
                  'labels': 'series labels (list of str)',
                  'colors': "colors for series (list of str hex colors, e.g. ['#ff0000', '#00ff00'])",
                  'x_labels': 'labels for x values (list of str) [optional]',
                }
    
    id = 'webfxchart'
    style = 'bar'
    width = 400
    height = 400
    x_ticks = None
    y_ticks = None
    y_max = None
    labels = []
    colors = ['red', 'green', 'blue', '#ffff00', '#ff00ff', '#00ffff'] # some default colors
    x_labels = []
    
    #c.setDefaultType(${STYLE_MAP[style]});
    template = """
    <div id="${id}" class="chart" style="margin: 0 auto 0 auto; width: ${width}px; height: ${height}px;">
        <script type="text/javascript">
            var labels = ${str(labels)};
            var colors = ${str(colors)};
            var data = ${str(data)};
            var x_labels = ${str(x_labels)};
            var y_max = ${y_max or max(map(max, data))};
            var c = new Chart(document.getElementById('${id}'));
            /* was here */
            c.setDefaultType(CHART_BAR);
            c.setGridDensity(${x_ticks or 'data[0].length'}+1, ${y_ticks or y_max}+1);
            c.setGridDensity(data[0].length+1, y_max+1); // c.setGridDensity(6,6);
            c.setVerticalRange(0, y_max);
            if (${y_max or -1} > 0) { c.setVerticalRange(0, ${y_max or -1}); }
            if (x_labels.length > 0) { c.setHorizontalLabels(${str(labels)}); }
            for (x=0; x &lt; data.length; x++) { c.add(labels[x], colors[x], data[x]); }
            c.draw();
        </script>
    </div>
    """
    
    
class WebFXChartDesc(WidgetDescription):
    """
    http://webfx.eae.net/dhtml/chart/chart.html
    """
    name = "WebFXChart"
    seriesA = [1, 2, 3, 4, 5]
    seriesB = [1, 1, 1, 2, 2]
    seriesC = [2, 3, 4, 2, 2]
    data = [seriesA, seriesB, seriesC]
    labels = ['A', 'B', 'C']
    x_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    
    for_widget = WebFXChart(data=data, labels=labels, x_labels=x_labels, style='stacked_bar')
